package com.cheng.student.controller.servlet;

import com.cheng.student.beans.Teacher;
import com.cheng.student.service.TeacherServiceImpl;
import com.cheng.student.service.interfaces.TeacherService;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "TeacherLoginServlet", value = "/login/TeacherLoginServlet")
public class TeacherLoginServlet
        extends HttpServlet
{
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException
    {
        //工资号
        String payrollNumber = request.getParameter("payrollNumber");
        //密码
        String password = request.getParameter("password");
        //验证码
        String checkCode = request.getParameter("checkCode");
        //设置字符集
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        //合理性校验
        //工资号为空
        if (payrollNumber == null || "".equals(payrollNumber))
        {
            response.setHeader("loginInformation","payrollNumberNull");
            return;
        }
        //密码为空
        if (password == null || "".equals(password))
        {
            response.setHeader("loginInformation","passwordNull");
            return;
        }
        //验证码为空
        if (checkCode == null || "".equals(checkCode))
        {
            response.setHeader("loginInformation","checkCodeNull");
            return;
        }

        //验证码校验
        //验证通过
        if(checkCode.equals(request.getSession().getAttribute("verificationCode"))){ }
        //验证码错误
        else
        {
            response.setHeader("loginInformation","checkCodeWrong");
            return;
        }
        //账号密码校验
        TeacherService teacherService = new TeacherServiceImpl();

        Teacher teacher = teacherService.loginTeacher(payrollNumber, password);

        //工资号或密码错误
        if(teacher == null)
        {
            response.setHeader("loginInformation","InformationWrong");
            return;
        }

        //通过
        //将查到的teacher对象存入session并设置存活时间为5分钟（五分钟后未进行任何操作则自动解除登录）
        request.getSession().setAttribute("teacher",teacher);

        request.getSession().setAttribute("power",teacher.getPower());

        request.getSession().setMaxInactiveInterval(300);

        //跳转到这个页面
        response.setHeader("href","/teacQuery.html");


    }
}
